# -*- encoding:utf-8 -*-
# @time: 2023/3/20 23:40
# @author: Maxs_hu
from web import models
from web.forms.level import LevelModelForm
from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse


def level_list(request):
    if request.method == "GET":
        queryset = models.Level.objects.filter(active=1)  # 查出所有级别
        return render(request, 'level_list.html', {'queryset': queryset})


def level_add(request):
    if request.method == 'GET':
        form = LevelModelForm()
        return render(request, 'level_add.html', {'form': form})

    form = LevelModelForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'level_add.html', {'form': form})
    # print(form.cleaned_data)
    form.save()  # ModelForm中提供的保存数据的方式
    return redirect(reverse('level_list'))


def level_edit(request, pk):
    user_info = models.Level.objects.filter(active=1, id=pk).first()
    if request.method == 'GET':
        form = LevelModelForm(instance=user_info)  # 插入原始数据. 实例
        # print(form)
        return render(request, 'level_edit.html', {'form': form})

    form = LevelModelForm(data=request.POST, instance=user_info)  # 获取到的值+原始值 -> 后面可以做更新
    if not form.is_valid():
        return render(request, 'level_edit.html', {'form': form})
    # print(form.cleaned_data)
    form.save()  # 更新
    return redirect(reverse('level_list'))


def level_delete(request, pk):
    if models.Customer.objects.filter(level_id=pk).exists():  # 如果当前level的被关联. 不删除
        return redirect(reverse('level_list'))
    models.Level.objects.filter(active=1, id=pk).update(active=0)  # 逻辑删除. 将active变成0
    return redirect(reverse('level_list'))
